package com.Linngdu664.drglaserpointer.event;

import com.Linngdu664.drglaserpointer.client.render.LaserRenderer;
import com.Linngdu664.drglaserpointer.client.render.TextRenderer;
import com.Linngdu664.drglaserpointer.item.ItemRegistry;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.client.event.RenderLevelStageEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;

public class LevelRenderEvent {
    public static boolean pickFlag = false;
    private Vec3 pos1;
    private TextComponent blockName;
    private BlockState blockState;

    @SubscribeEvent
    public void renderLevelStage(RenderLevelStageEvent event) {
        if (event.getStage().equals(RenderLevelStageEvent.Stage.AFTER_PARTICLES)) {
            Player player = Minecraft.getInstance().player;
            if (player.getItemInHand(InteractionHand.MAIN_HAND).is(ItemRegistry.LASER_POINTER.get())) {
                float ticks = event.getPartialTick();
                HitResult hitResult = player.pick(100, ticks, false);
                Vec3 pos = hitResult.getLocation();
                Vec3 viewVec = player.getViewVector(ticks);
                double viewX = viewVec.x;
                double viewZ = viewVec.z;
                double dis = Math.sqrt(viewX * viewX + viewZ * viewZ);
                viewX /= dis;
                viewZ /= dis;
                LaserRenderer.drawLine(event, player.getEyePosition(ticks).add(-viewZ * 0.04, -0.015, viewX * 0.04), pos, 255, 165, 0);
                if (pickFlag) {
                    pickFlag = false;
                    pos1 = new Vec3(pos.x, pos.y, pos.z);
                    BlockPos blockPos = ((BlockHitResult) hitResult).getBlockPos();
                    blockState = player.level.getBlockState(blockPos);
                    blockName = new TextComponent("");
                    blockName.append(blockState.getBlock().getName());
                }
            }
            if (pos1 != null && blockState != null && !blockState.getBlock().equals(Blocks.AIR)) {
//                TextRenderer.renderText(event, (TextComponent) player.getName(), pos1.add(0, 0.2, 0));
                TextRenderer.renderText(event, new TextComponent(String.format("%.2fm", pos1.distanceTo(player.getEyePosition()))), pos1);
//                TextRenderer.renderText(event, blockName, pos1.subtract(0, 0.2, 0));
            }
        }
    }
}
